package com.yuejie.crawler;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuejie.bean.ResultPojo;
import com.yuejie.bean.SongPojo;

public class LyricCrawlerInGeci {
	private static final Logger connlogger = LoggerFactory.getLogger("connLogger");
	private static final Logger resultlogger = LoggerFactory.getLogger("resultLogger");

	private final HttpClient httpClient;
	private final HttpContext context;

	public static void main(String[] args) {

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80,PlainSocketFactory.getSocketFactory()));
		ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
		HttpClient hc = new DefaultHttpClient(cm);
		
		//设置代理
		HttpHost proxy = new HttpHost("173.242.123.178", 80);
		hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

		LyricCrawlerInGeci h = new LyricCrawlerInGeci(hc);
		SongPojo s = new SongPojo();
		s.setId("123");
		s.setSinger_name("王菲,yjz");
		s.setSong_name("执迷不悔");
		ResultPojo r = h.parseSearchResultPage(s);
		System.out.println(r.getCode() + ":" + r.getLyric());

	}

	public LyricCrawlerInGeci(HttpClient httpClient) {
		this.httpClient = httpClient;
		this.context = new BasicHttpContext();
	}

	/**
	 * @param song
	 * @param artist
	 * @return lrc
	 */
	public ResultPojo parseSearchResultPage(SongPojo s) {

		s.setSinger_name(s.getSinger_name().split(",")[0]);
		s.setSong_name(s.getSong_name().split("\\(")[0]);
		ResultPojo result = new ResultPojo();
		try {
			Set<String> set = new HashSet<String>();
			String encodedsong = URLEncoder.encode(s.getSong_name(), "UTF-8");
			encodedsong = encodedsong.replace("+", "%20");
			String urlstring = "http://geci.me/search/song/" + encodedsong + "/1";
			URI uri = new URI(urlstring);
			set = this.getSongDetailLinks(set, uri);

			if (set.isEmpty()) {
				result.setCode(ResultPojo.StateCode.SONG_NOT_FOUND);
				resultlogger.error(s.getSinger_name() + ":" + s.getSong_name() + ":" + s.getId() + " [Empty search result for this song.]");
			} else {
				for (String e : set) {

					result = this.parseSongDetailPage(s, e, result);
					if (!"".equals(result.getLyric()) &&

					result.getLyric() != null) {
						return result;
					}
				}

			}

		} catch (MalformedURLException e) {
			// URL转换异常。
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " [error occured when creat a url object.] in method (parseSearchResultPage)"
					+ e.toString());
		} catch (IOException e) {
			// Jsoup解析异常。
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name() + ":" + s.getSong_name() +

			":" + s.getId()
					+ " [error occured when parse the url.] in method (parseSearchResultPage)"
					+ e.toString());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 * @param s
	 *             查询参数
	 * @param urlstring
	 *             需要解析的url
	 * @param result
	 *             返回的Result
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	private ResultPojo parseSongDetailPage(SongPojo s, String uristring, ResultPojo

	result) throws MalformedURLException, IOException, URISyntaxException {

		URI uri = new URI(uristring);
		String pagecontent = this.executeGet(uri);
		Document doc = Jsoup.parse(pagecontent);
		Elements artistnodes = doc.select("a[href^=/artist/]");
		Element artisnode = artistnodes.get(0);
		String artist_innode = artisnode.ownText();

		if (artist_innode.contains(s.getSinger_name())
				|| s.getSinger_name().contains(artist_innode)) {
			Elements lrcnodes = doc.select("#lyric p");
			Element lrcnode = lrcnodes.get(0);
			if (lrcnode.text().length() > 15) {
				// 存在歌词，并返回
				result.setCode(ResultPojo.StateCode.SUCCESS);
				result.setLyric(lrcnode.text());
				return result;
			} else {
				// 找到对应歌手和歌词名的歌曲，但是没有歌词
				result.setCode(ResultPojo.StateCode.LYRIC_IS_EMPTY);
				return result;
			}
		} else {
			if (result.getCode() == 0) {
				result.setCode(ResultPojo.StateCode.ARTIST_NOT_MATCH);
			}
			return result;
		}
	}

	/**
	 * 
	 * @param s
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	private Set<String> getSongDetailLinks(Set<String> s, URI uri) throws

	MalformedURLException, IOException, URISyntaxException {

		String pagecontent = this.executeGet(uri);
		Document doc = Jsoup.parse(pagecontent, "http://geci.me");
		Elements songdetaillink = doc.select("a[href^=/song/]");
		if (songdetaillink.isEmpty()) {
			return s;
		} else {
			for (Element src : songdetaillink) {
				String href = src.attr("abs:href");
				s.add(href);
			}

			// 找到前一页和后一页的元素集合。
			Elements next_previous_page_link = doc.select("a[href^=/search/song/]");
			if (next_previous_page_link.isEmpty()) {
				return s;
			} else if (next_previous_page_link.size() == 1) {
				if (next_previous_page_link.first().html().contains("gt")) {
					uri = new URI(next_previous_page_link.last().attr("abs:href").replace(" ", "%20"));
					return this.getSongDetailLinks(s, uri);
				} else {
					return s;
				}

			} else if (next_previous_page_link.size() == 2) {
				if (next_previous_page_link.last().html().contains("gt")) {
					uri = new URI(next_previous_page_link.last().attr("abs:href").replace(" ", "%20"));
					return this.getSongDetailLinks(s, uri);
				} else {
					return s;
				}

			} else {
				return s;
			}

		}
	}

	private String executeGet(URI uri) throws ClientProtocolException, IOException  {
		HttpGet httpget = new HttpGet(uri);
		httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2");
		HttpResponse response = this.httpClient.execute(httpget, this.context);
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, "UTF-8");

	}

}
